﻿using System;
using System.Configuration;
using System.IO;
using System.Web;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

using Outcoder.InversionOfControl.Unity;
using Outcoder.Services;

namespace Outcoder.Calcium.ClientServices
{
	public class Global : HttpApplication
	{
		protected void Application_Start(object sender, EventArgs e)
		{
			/* This causes log4net to initalise. 
			 * We need this for the ClientLogging library 
			 * to be able to log using log4net. 
			 * It triggers reading the config etc. [DV] */
			string rootDirectory = Server.MapPath("~");
			log4net.Config.XmlConfigurator.Configure(new FileInfo(rootDirectory + "Log4Net.config"));
			Log.Info("Web application starting.");

			try
			{
				var container = new UnityContainer();
				var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
				section.Configure(container);
				container.InitializeServiceLocator();
			}
			catch (Exception ex)
			{
				Log.Fatal("Unable to initialize Unity from configuration.", ex);
				throw;
			}

			try
			{
				ConfigureUnity();
			}
			catch (Exception ex)
			{
				Log.Fatal("Unable to initialize Unity core services.", ex);
				throw;
			}
		}

		void ConfigureUnity()
		{
			var communicationService = new CommunicationService();
			Dependency.Register<ICommunicationService>(communicationService);
			Dependency.Register<IDialogService, ServerSideDialogService>();
		}

		protected void Session_Start(object sender, EventArgs e)
		{

		}

		protected void Application_BeginRequest(object sender, EventArgs e)
		{

		}

		protected void Application_AuthenticateRequest(object sender, EventArgs e)
		{

		}

		protected void Application_Error(object sender, EventArgs e)
		{

		}

		protected void Session_End(object sender, EventArgs e)
		{

		}

		protected void Application_End(object sender, EventArgs e)
		{

		}
	}
}